#include "MatrixSerialize.h"
#include "StringHelper.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
COpenCVSerializer::COpenCVSerializer(void)
{

}

COpenCVSerializer::~COpenCVSerializer(void)
{

}

template <class T> 
 void convertFromString(T &value, const std::string &s) {
	   std::stringstream ss(s);
	  ss >> value;
	 }

IplImage* COpenCVSerializer::Load(const char* fileName)
{
	std::ifstream inFile(fileName);
	
	IplImage* pImg = NULL;
	std::string sSize;
	if ( !getline(inFile, sSize) )
		return NULL;

	std::vector<std::string> vSize;
	trim(sSize);
	split(sSize,vSize,",");
	int rows;
	int cols;
	convertFromString(rows,vSize[0]);
	convertFromString(cols,vSize[1]);

	pImg = cvCreateImage(cvSize(cols,rows),IPL_DEPTH_8U,1);

	std::string sData;
	unsigned short num;
	int rowIndex = 0;
	while (getline(inFile, sData)) 
	{
		std::cout << sData.data() <<std::endl;
	    trim(sData);
		std::vector<std::string> vStr;
		vStr = split(sData, vStr, ",");
		unsigned char* rowPtr = (unsigned char*)(pImg->imageData + rowIndex * pImg->widthStep);
		for (int colIndex =0 ; colIndex<vStr.size(); colIndex++)
		{
			if (vStr[colIndex] != "")
			{
				convertFromString(num,vStr[colIndex]);
				 rowPtr[colIndex] = num;
			}
		}
	 
		rowIndex ++;

	}
	inFile.close(); 
	COpenCVSerializer::Save("2.txt",pImg);
	return NULL;

}

bool  COpenCVSerializer::Save(const char* fileName,IplImage* pImg)
{

	int height = pImg->height;
	int width = pImg->width;
	std::ofstream outFile(fileName);
	outFile<<height << ","<< width<< std::endl;
	for (int i = 0; i < pImg->height; i++)
	{
		unsigned char* rowPtr = (unsigned char*)(pImg->imageData + i * pImg->widthStep);
			std::string strOutput;
		for (int j =0; j < pImg->width; j++)
		{

			    char num[10]; 
		        itoa(rowPtr[j],num,10);
			 	strOutput += num;
				strOutput += ",";
		}
		outFile << strOutput.data() << std::endl;

	}
	outFile.flush();
	outFile.close();
	return true;
}

bool  COpenCVSerializer::Save(const char* fileName,CvMat* pMat)
{

	int rows  = pMat->height;
	int width = pMat->width;
	std::ofstream outFile(fileName);
	outFile<<rows << ","<< width<< std::endl;
	for (int i = 0; i < pMat->rows; i++)
	{
		unsigned char* rowPtr = (unsigned char*)(pMat->data.ptr + i * pMat->width);
		std::string strOutput;
		for (int j =0; j < pMat->cols; j++)
		{

			char num[10]; 
			itoa(rowPtr[j],num,10);
			strOutput += num;
			strOutput += " ";
		}
		outFile << strOutput.data() << std::endl;

	}
	outFile.flush();
	outFile.close();
	return true;
}